<?php

namespace app\beautiful\controller\admin\partner;

use app\BaseController;

use app\beautiful\model\CouponModel;
use app\beautiful\model\GiftbagModel;
use app\beautiful\model\PartnerGiftbagModel;
use app\common\logic\DataLogic;

use app\beautiful\logic\PartnerLogic;

use app\beautiful\model\member\MemberBalanceModel;

use app\beautiful\model\member\MemberIntegralModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\partner\PartnerCommissionModel;

use app\beautiful\model\partner\PartnerSettingModel;

use app\beautiful\model\partner\PartnerWithdrawModel;

use app\beautiful\model\PartnerModel;
use think\Model;


class Partner extends BaseController{

    protected $name='合伙人';



    public function index()

    {

        $type=$this->request->param('type/d',1);

        $mobile=$this->request->param('mobile');

        $status=$this->request->param('status/d',1);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['role_id','=',$type]

        ];

        if(!empty($mobile)) $where[]=['mobile','=',$mobile];

        if($type==1) $where[]=['status','=',$status];



        $partner_model= new PartnerModel();

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format'];

        if($type==1) $append=['is_expire','add_time_format'];

        $return = DataLogic::getDataList($partner_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);

    }



    public function show()

    {

        $return=[];

        //获取股金数据

        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){

            return $this->error('您还未设置合伙设置，请先设置');

        }

        $return['dividend_ratio_data']=$partner_setting->dividend_ratio_data;



        $partner_id = $this->request->param('partner_id/d',0);

        if($partner_id==0) return $this->success($return);



        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');



        $detail=[

            'name'=>$partner->name,

            'mobile'=>$partner->mobile,

            'custom_name'=>$partner->custom_name,

            'custom_rate'=>$partner->custom_rate,

            'expire_time'=>$partner->expire_time,

        ];

        $return['detail']=$detail;



        return $this->success($return);

    }



    public function detail()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $role_id=$this->request->param('role_id/d',0);

        if(!in_array($role_id,[1,2,3,4,5,6])) return $this->error('参数错误');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

        $partner->append(['role_means']);



        if(null === $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find()){

            return $this->error($this->name.'暂未激活');

        }



        $customer_num=MemberModel::where([

            ['shop_id','=',$this->request->shopId],

            ['pid','=',$pmember->member_id]

        ])->count() ?? 0;



        $detail=[

            'name'=>$partner->name,

            'mobile'=>$partner->mobile,

            'expire_time'=>$partner->expire_time,

            'share_capital'=>$partner->share_capital,

            'profit_rate'=>$this->getShareRate($partner->share_capital),

            'profit'=>$partner->profit,

            'withdrawable_profit'=>$partner->withdrawable_profit,

            'role_means'=>$partner->role_means,

            'customer_num'=>$customer_num,

            'custom_name'=>$partner->custom_name,

            'custom_rate'=>$partner->custom_rate,

        ];



        if($role_id==2){

            $detail['monetary'] = PartnerCommissionModel::where([

                ['shop_id','=',$this->request->shopId],

                ['partner_id','=', $partner->partner_id]

            ])->sum('monetary');

            $detail['commission'] = PartnerCommissionModel::where([

                ['shop_id','=',$this->request->shopId],

                ['partner_id','=', $partner->partner_id]

            ])->sum('commission');

        }

        $return['detail']=$detail;



        return $this->success($return);

    }



    public function getPartnerIncomeList()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $role_id=$this->request->param('role_id/d',0);

        $month=$this->request->param('month');

        //if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');


        $where=[

            ['shop_id','=',$this->request->shopId],

            ['partner_id','=',$partner_id],

        ];

        if(!empty($month)) $where[]=['month','=',$month];



        $commission_model= new PartnerCommissionModel();

        if($role_id==3 || $role_id==1){

            $commission_model=$commission_model->with(['member']);

        }

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format'];



        $return = DataLogic::getDataList($commission_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);



        return $this->success($return);

    }



    public function getPartnerCustomerList()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $role_id=$this->request->param('role_id/d',0);

        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');



        if(null === $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find()){

            return $this->error($this->name.'不存在');

        }



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['pid','=',$pmember->member_id],

        ];

        $memberModel=new MemberModel();

        $order=['add_time'=>'desc'];

        $append=['add_time_format'];

        $field='member_id,nick_name,face,mobile,pid,add_time';

        $data=DataLogic::getDataList($memberModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);



        //处理数据

        $lists=$data['list'];

        if(empty(!$lists)){

            $memberIds = $moneys= [];

            foreach($lists as $val){

                $memberIds[$val['member_id']] = $val['member_id'];

            }

            if(!empty($memberIds)){

                $PartnerCommissionModel = new PartnerCommissionModel();

                $moneys =  $PartnerCommissionModel->getMonetarySumByPartnerId($memberIds);

            }

            foreach ($lists as $k => $list){

                $lists[$k]['money']=$moneys[$list['member_id']] ?? 0;

            }

        }

        $data['list']=$lists;

        return $this->success($data);

    }



    public function bindMember()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $role_id=$this->request->param('role_id/d',0);

        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');

        $mobile=$this->request->param('mobile');

        if(empty($mobile)) return $this->error('请输入手机号');

        if(!is_mobile($mobile)) return $this->error('请输入正确的手机号');



        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');



        if(null === $pmember = MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find()){

            return $this->error($this->name.'不存在');

        }



        $member = MemberModel::where([

                ['mobile','=',$mobile],

                ['shop_id','=',$this->request->shopId],

            ])->find();

        if($member == null){

            $member = new MemberModel();
            $member->mobile=$mobile;
            $member->shop_id = $this->request->shopId;
            $member->nick_name = 'V'.$this->request->shopId.date('md').mt_rand(100000,999999); //防止有特殊字的用户
            $member->save();

        }


        if($member->pid == $pmember->member_id){

            return $this->error('该手机号已成功绑定');
        }

        if($member->pid >0 ){
            return $this->error('该手机号已绑定其他合伙人，请重新输入');
        }


        $partner_logic= new PartnerLogic($this->request->shopId);

        $res= $partner_logic->bindPartner($member->member_id,$pmember->member_id,true);

        return $this->success('添加成功');



    }



    public function getPartnerDetailWithdrawList()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $role_id=$this->request->param('role_id/d',0);

        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');



        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

//        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['partner_id','=',$partner_id]

        ];

        $partner_withdraw_model= new PartnerWithdrawModel();

        $order=['add_time'=>'desc'];

        $field='*';

        $append=['add_time_format','status_means'];

        $return= DataLogic::getDataList($partner_withdraw_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);



        return $this->success($return);

    }



    protected function getShareRate($share_capital)

    {

        $commissionRate = 0;

        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){

            return $commissionRate;

        }



        if(empty($partner_setting->dividend_ratio_data)) return $commissionRate;



        foreach($partner_setting->dividend_ratio_data as $val){

            if($val['share_capital'] <= $share_capital && $val['dividend_ratio'] >= $commissionRate){

                $commissionRate =  $val['dividend_ratio'];

            }

        }



        if($commissionRate <= 0 || $commissionRate >= 100) return 0;



        return $commissionRate;

    }



    public function save()

    {

        $type=$this->request->param('type/d');

        $partner_id = $this->request->param('partner_id/d',0);

        $name=$this->request->param('name');

        $mobile=$this->request->param('mobile');

        $custom_name=$this->request->param('custom_name');

        $custom_rate=$this->request->param('custom_rate/f',0);

        $expire_time=$this->request->param('expire_time');

        $index= $this->request->param('index/d',-1);



        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){

            return $this->error('您还未设置合伙设置，请先设置');

        }



        //判断传来的参数

        if(!in_array($type,[1,2,3,4])) return $this->error('参数错误');

        if(empty($name)) return $this->error('请输入合伙人姓名');

        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入合伙人手机号');

        if(in_array($type,[1,4])){

            if(empty($expire_time)) return $this->error('请选择过期时间');

            if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');

        }

        if($type==1){

            if($index<0) return $this->error('请选择股金');

            $dividend_ratio_data=$partner_setting->dividend_ratio_data;

            if(!isset($dividend_ratio_data[$index])) return $this->error('未找到股金，请重新选择');

            $share_capital=$dividend_ratio_data[$index]['share_capital'];

        }

        if($type==4){

            if(empty($custom_name)) return $this->error('请输入自定义名称');

            if(empty($custom_rate) || $custom_rate <=0 ||$custom_rate>100) return $this->error('请输入比例，且不能小于0或者大于100');

        }



        if($partner_id != 0){

            if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

            if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

            if($partner->is_delete == 1) return $this->error($this->name.'不存在');

            if($partner->role_id != $type) return $this->error($this->name.'不存在');

            //判断是否已经存在

            if($partner->mobile != $mobile){

                if(null !== PartnerModel::where([

                        ['shop_id','=',$this->request->shopId],

                        ['is_delete','=',0],

                        ['mobile','=',$mobile],

                    ])->find()){

                    return $this->error('这个手机号已经存在合伙人了');

                }

            }



        }else{

            $partner = new PartnerModel();

            $partner->shop_id = $this->request->shopId;

            $partner->role_id=$type;

            if(null !== PartnerModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['is_delete','=',0],

                    ['mobile','=',$mobile],

                ])->find()){

                return $this->error('这个手机号已经存在合伙人了');

            }

        }



        $partner->name=$name;

        $partner->mobile=$mobile;

        if(in_array($type,[1,4])){

            $partner->expire_time=$expire_time;

        }

        if($type==1){

            $partner->share_capital=$share_capital;

        }

        if($type==4){

            $partner->custom_name=$custom_name;

            $partner->custom_rate=$custom_rate;

        }

        $partner->save();



        if(null ===  MemberModel::where([

                ['shop_id','=',$this->request->shopId],

                ['mobile','=',$partner->mobile]

            ])->find()){

            $member = new MemberModel();

            $member->mobile=$mobile;

            $member->shop_id = $this->request->shopId;

            $member->nick_name = '未设置'; //防止有特殊字的用户

            $member->save();

        }



        return $this->success('保存成功');



    }



    public function delay()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        $expire_time=$this->request->param('expire_time');



        if(empty($expire_time)) return $this->error('请选择过期时间');

        if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if($partner->role_id != 1) return $this->error($this->name.'不存在');

        if($partner->status == -1 ) return $this->error($this->name.'已经退股了,无法删除');



        $partner->expire_time = $expire_time;

        $partner->save();

        return $this->success('操作成功');

    }





    public function withdrawal()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if(!in_array($partner->role_id,[1,4])) return $this->error($this->name.'不存在');

        if($partner->status == -1 ) return $this->error($this->name.'已经退股了，请勿重复操作');

        //其他判断，待补充



        $partner->status=-1;

        $partner->save();

        return $this->success('操作成功');

    }



    public function del()

    {

        $partner_id = $this->request->param('partner_id/d',0);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        if(in_array($partner->role_id,[1,4])){

            if($partner->status != -1) return $this->error('还未退股，无法删除');

        }

        //其他判断，待补充



        $partner->is_delete=1;

        $partner->save();

        return $this->success('操作成功');

    }


    //合伙人礼包
    public function savePartnerGiftbag()
    {

        $partner_id = $this->request->param('partner_id/d',0);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');

        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');

        $partner_giftbag_id=$this->request->param('partner_giftbag_id/d',0);

        $giftbag_id=$this->request->param('giftbag_id/d',0);

        $send_qty=$this->request->param('send_qty/d',0);

        if( $giftbag_id < 1){
            return $this->error('请选择礼包');
        }else{
            if(null === $giftbag = GiftbagModel::find($giftbag_id)){
                return $this->error('礼包不存在');
            }
        }

        if( $send_qty < 1){
            return $this->error('发放数量需要大于0');
        }


        if($partner_giftbag_id != 0){

            if(null === $partner_giftbag = PartnerGiftbagModel::find($partner_giftbag_id)){
                return $this->error('数据不存在');

            }else{
                $get_qyt = $partner_giftbag->send_qty - $partner_giftbag->remand_qty;
                if($send_qty < $partner_giftbag->remand_qty  ){
                    return $this->error('发放数量不能小于剩余数量:'.$partner_giftbag->remand_qty);
                }
            }

        }else{

            $partner_giftbag = new PartnerGiftbagModel();
            $get_qyt = 0;
        }

        $partner_giftbag->shop_id = $this->request->shopId;
        $partner_giftbag->partner_id  = $partner_id;
        $partner_giftbag->giftbag_id  = $giftbag_id;
        $partner_giftbag->send_qty=$send_qty;
        $partner_giftbag->remand_qty= $send_qty- $get_qyt;
        $partner_giftbag->update_time=$this->request->time();

        $partner_giftbag->save();
        return $this->success('保存成功');

    }

    public function getPartnerGiftbagList()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error('合伙人不存在');

        $where=[

            ['shop_id','=',$this->request->shopId],
            ['partner_id','=',$partner_id]

        ];

        $partner_giftbag = new PartnerGiftbagModel();

        $order=['update_time'=>'desc','add_time'=>'desc'];

        $field="partner_giftbag_id,giftbag_id,send_qty,remand_qty,add_time";

        $append=[];
        $return = DataLogic::getDataList($partner_giftbag,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        $return['new_list'] = [];
        foreach($return['list'] as $giftbag){
            $data['partner_giftbag_id'] = $giftbag['partner_giftbag_id'] ;
            $data['giftbag_id'] = $giftbag['giftbag_id'] ;
            $data['name'] = GiftbagModel::where('giftbag_id',$giftbag['giftbag_id'])->value('name');
            $data['send_qty'] = $giftbag['send_qty'] ;
            $data['remand_qty'] = $giftbag['remand_qty'];
            $data['add_time'] = date('Y-m-d H:i:s',$giftbag['add_time']);

            $return['new_list'][] =  $data;
        }

        unset($return['list']);
        $return['list'] = $return['new_list'];
        unset($return['new_list']);

        return $this->success($return);

    }

    public function delPartnerGiftbag()

    {

        $partner_giftbag_id=$this->request->param('partner_giftbag_id/d',0);


        if(null === $partner_giftbag = PartnerGiftbagModel::find($partner_giftbag_id)){

            return $this->error('礼包数据不存在');

        }


        if($partner_giftbag->shop_id !=$this->request->shopId){

            return $this->error($this->name.'不存在');

        }

        $partner_giftbag->delete();

        return $this->success('删除成功');

    }



}

